let socketTask = null;
let socketUrl = 'wss://lhz.rigourtech.com:8191/websocket';

export function connectSocket(callback) {

	if (socketTask && socketTask.readyState === 1) {
		callback && callback('already connected')
		return;
	}
	
	socketTask = uni.connectSocket({
		url: socketUrl,
		complete: (res) => {
			console.log("WebSocket connected successfully.");
		},
		fail(error) {
			console.error("Failed to connected:", error);
		},
	});

	socketTask.onOpen(() => {
		console.log('WebSocket连接已打开')
		callback && callback('WebSocket连接已打开');
	});

	socketTask.onMessage((res) => {
		let resultData = protoRoot.WrapperMessage.decode(new Uint8Array(res.data)); //decode数据
		var message = JSON.parse(resultData.textmessage.content);
		console.log('WebSocket接收到服务器推送的消息：', message)
	});
	
	socketTask.onClose((res) => {
		console.log('WebSocket连接被关闭');
	});

	socketTask.onError((err) => {
		console.error('WebSocket连接打开失败，请检查！', err);
	});
}

export function sendSocketMessage(data, callback) {
	if (!socketTask) {
		console.log('WebSocket连接被关闭');
		return;
	}
	
	let buffer = new Uint8Array(data).buffer;
	console.log('要发送的信息......', buffer);
	socketTask.send({
		data: buffer,
		fail: (err) => {
			console.log('发送失败了.....', err);
			callback && callback(err)
		},
		complete: (res) => {
			console.log('发送成功了.....', res);
			callback && callback(res)
			closeSocket();
		}
	})
}

export function closeSocket(callback) {
	if (socketTask) {
		socketTask.close({
			complete: (res) => {
				socketTask = null
				callback && callback(res)
			}
		})
	} else {
		callback && callback('socket already closed')
	}
}